<template>
  <div>
    <div v-if="pay">
      <div class="usertop bluebg">
        <span class="usubtit">充值中心</span>
      </div>
      <div class="userform">
        <el-form ref="form" :model="form" labelPosition="left" label-width="80px">
          <el-form-item label="充值账号" prop="username">
            <el-input v-model="username" readonly class='readonly inline'>
            </el-input>
            <span v-if="expiretime==0">(会员已过期)</span>
            <span v-else-if="expiretime==undefined"></span>
            <span v-else>(套餐剩余：{{expiretime}}天)</span>
            <!-- <span v-if="expiretime==0||expiretime==null||expiretime==undefined">(套餐剩余：{{expiretime}}天)</span> -->
          </el-form-item>
          <el-form-item label="充值余额" prop="amount">
            <el-input v-model="user.amount_desc" readonly class='readonly balance inline'></el-input>
            <span>(不包含VIP充值金额)</span>
          </el-form-item>
          <el-form-item label="充值項目" prop="order_type">
            <el-radio-group v-model="form.order_type" class="paymode" @change="radioChange1">
              <el-radio-button label="2" class="alipay"><span>VIP充值</span></el-radio-button>
              <el-radio-button label="1" class="wxpay_native"><span>余额充值</span></el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="充值金额" prop="money" v-if="form.order_type==1">
            <el-input v-model="form.money" placeholder="请输入金额"></el-input>
          </el-form-item>
          <el-form-item v-if="form.order_type==2">
            <p>1、VIP充值金额不计入其内，只计有效时间；</p>
            <p class="addmargin">2、充值规则：{{config.vip_price}}起VIP价格，可享受{{config.vip_days}}天；</p>
          </el-form-item>
          <!-- <el-form-item v-if="payArray"> -->
          <el-form-item v-if="!order_sn">
            <el-button @click="oncreate" class="to-pay">确认充值</el-button>
          </el-form-item>
          <el-form-item label="充值方式" prop="paymode" v-if="payArray.length!==0">
            <el-radio-group v-model="form.paymode" class="paymode" @change="radioChange2">
              <template v-for="item in payArray">
                <el-radio-button :label="item.payment_code" :class="item.payment_code">
                  <i class='iconfont iconweixin' v-if="item.payment_code=='wxpay_native'"></i>
                  <i class='iconfont icon-zhifubao' v-if="item.payment_code=='alipay'"></i>
                  <span>{{item.payment_name}}</span>
                </el-radio-button>
              </template>

              <!-- <el-radio-button label="2" class="zhifubao"><i class='iconfont icon-zhifubao'></i><span>支付宝支付</span></el-radio-button> -->
              <!--                    <el-radio-button label="useAmount" class="alipay" v-if="form.order_type==2">使用余额</el-radio-button>-->
            </el-radio-group>
            <!-- <el-button class="alipay" @click="useAmount">使用余额</el-button> -->
          </el-form-item>
          <el-form-item label="抵扣余额" prop="decount" v-if="balancePayEnabled">
            <el-input v-model="config.vip_price" readonly class='red inline'></el-input>
            <span>(实际扫描支付时，VIP充值金额，则可按照该金额，进行抵扣支付)</span>
          </el-form-item>
          <el-form-item v-if="balancePayEnabled">
            <el-button @click="getPayRequestDecount" class="to-pay">确认充值</el-button>
          </el-form-item>
          <!-- <el-form-item >
                  <el-checkbox v-model="form.checked" v-if="paycode">同意服务条款及隐私政策</el-checkbox>
              </el-form-item> -->

          <!--  <el-form-item>
                <el-button  @click="onSubmit" class="bluebtn">确认充值</el-button>              
              </el-form-item> -->
        </el-form>
        <div>
          <div class="codebox" v-if="showcode">
            <img :src="url" alt="">
          </div>
        </div>
        <!--  <button @click="test">已支付</button> -->
      </div>

      <!-- <iframe width="400" height="400"  frameborder="0"  src="https://www.w3school.com.cn/html/html_iframe.asp"></iframe> -->
    </div>
    <div v-else>
      <div class="usertop bluebg flexrow">
        <i class="el-icon-success"></i>
        <span class="usubtit">支付成功</span>
      </div>
      <div class="userform">
        <el-form ref="form2" :model="form" labelPosition="left" label-width="80px">
          <el-form-item label="充值项目" prop="order_type">
            <el-input v-model="form2.order_type" readonly class='readonly'></el-input>
          </el-form-item>
          <el-form-item label="支付方式" prop="paycode">
            <el-input v-model="form2.paycode" readonly class='readonly'></el-input>
          </el-form-item>
          <el-form-item label="订单金额" prop="money">
            <el-input v-model="order.amount" readonly class='readonly moneyinput'>
              <!--  <span slot="prefix">￥</span> -->
              <span slot="suffix">元</span>
            </el-input>
          </el-form-item>
          <el-form-item>
          </el-form-item>
        </el-form>

      </div>
      <div class="tips flexrow">
        <i class="el-icon-question"></i>
        <p>昌友税法查询平台不会以订单异常、系统升级等理由，通过任何方式发送给您退款链接，请您谨防<span>钓鱼链接或诈骗电话</span>！</p>
      </div>
      <div class="bluebtn" @click='back'>返回充值中心</div>
    </div>


    <el-dialog :visible.sync="payCodeDia" class="notedia" center>
      <p slot="title" class="dialog-title">
        支付
      </p>

      <div class="iframeBox">
        <iframe id="payiframe" width="400" height="300" frameborder="0" scrolling="no" :src="iframeUrl"></iframe>
        <button>关闭</button>
      </div>
    </el-dialog>

  </div>

</template>
<script>
  import global_ from '../../../components/Global'//引用模块进来
  import axios from 'axios'
  import storage from '../../../storage/index'
  import { updateUserInfo } from "../../../util/common";

  export default {
    name: 'UserPay',
    inject: ['reload'],
    data() {
      return {
        config: {},
        user: {},
        username: localStorage.getItem("username"),
        pay: true,
        order_type: '2',
        order_sn: '',
        url: '',
        payArray: [],
        paycode: '',
        payCodeDia: false,
        iframeUrl: '',
        myVal: false,
        timer: null,
        order: {},
        form: {
          order_type: '2',
          amount: 0,
          money: '',
          paymode: '',
          checked: '',
          decount: 0
        },
        form2: {
          order_type: '',
          paycode: '',
          money: ''
        },
        readonly: 'true',
        decountShow: false,
        showcode: false,
        expiretime: 0,
        isClick: false,
      }
    },
    computed: {
      // username(){
      //   return this.$store.state.username
      // }
      balancePayEnabled() {
        return this.order_sn && this.form.order_type == 2 && this.form2.paycode == '余额支付'
      }
    },
    methods: {
      onSubmit() {
        this.$router.push({ name: 'UserPay_end' })
      },
      back() {
        this.pay = false
        this.reload()
      },
      radioChange1(e) {
        this.payArray = []
        this.order_sn = ''
        this.showcode = false
        this.form2.paymode = ''
        this.isClick = false
        // if(!this.isClick){
        console.log(e)
        this.form2.order_type = e
        this.form.order_type = e
        // }else{
        // this.$confirm('是否需要修改充值项目?', '修改充值项目', {
        //     confirmButtonText: '确定',
        //     cancelButtonText: '取消',
        //     type: 'warning'
        //   }).then(() => {
        //     this.onload()
        //   }).catch(() => {
        //     console.log('quxiao')    
        //   });
        // }
      },
      async oncreate() {
        this.user = await updateUserInfo();
        console.log(JSON.stringify(this.user))

        let order_type = this.form.order_type
        if (order_type == 1) {
          let amount = this.form.money
          if (amount == null || amount == 0) {
            this.$message({
              dangerouslyUseHTMLString: true,
              message: '<p>请输入金额~</p>',
              center: true,
              offset: 300,
              duration: 1000,
              type: 'error'
            })
          } else {
            this.form2.money = amount
            this.creatOrder()
          }
        } else {
          //VIP充值金额为100 
          this.form2.money = 100
          this.creatOrder()
        }
      },
      creatOrder() {
        axios.post('/recharge/create', {
          order_type: this.form.order_type,
          amount: this.form2.money
        }).then((res) => {
          res = res.data
          if (res.status == 200) {
            console.log(res)
            this.order_sn = res.data.order_sn
            this.order = res.data
            this.onpayModel(res.data.order_sn)
          }
        })
      },
      onpayModel(sn) {
        axios.get('/recharge/payment?order_sn=' + sn)
          .then((res) => {
            res = res.data
            if (res.status == 200) {
              console.log(res)
              this.payArray = res.data.payment_list

              // 默认支付宝支付
              this.radioChange2('alipay')
            }
          })
      },
      async radioChange2(e) {
        this.user = await updateUserInfo();
        this.form.paymode = e;
        this.showcode = false;
        if (!this.isClick) {
          this.paycode = e
          this.isClick = true

          if (e == 'wxpay_native') {
            this.form2.paycode = '微信支付'
            this.getPayRequest()
          } else if (e == 'alipay') {
            this.form2.paycode = '支付宝支付'
            this.getPayRequest()
          } else if (e == 'balance') {
            if (this.form2.money <= this.user.amount) {
              this.form.decount = this.form2.money
              this.form2.paycode = '余额支付'
              this.decountShow = true
            } else {
              this.$message({
                dangerouslyUseHTMLString: true,
                message: '<p>余额不足，请充值~</p>',
                center: true,
                offset: 300,
                duration: 1000,
                type: 'warning'
              })
            }
          }
        } else {
          this.$confirm('是否需要修改支付方式?', '修改支付方式', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.isClick = false
            clearInterval(this.timer)
            this.radioChange2(e)
          }).catch(() => {
            console.log('quxiao')
          });
        }

        //弹出iframe
        // this.payCodeDia = true
        // this.iframeUrl = 'http://app.yejianping.cn/open/payment/recharge_order?order_sn='+this.order_sn+'&payment_code='+e

      },
      getPayRequest() {
        axios.get('http://app.yejianping.cn/open/payment/' + this.paycode + '_qrcode?order_sn=' + this.order_sn)
          .then((res) => {
            this.showcode = true
            console.log(res)
            //res = res.data
            if (res.status == 200) {
              this.url = 'http://app.yejianping.cn/open/payment/' + this.paycode + '_qrcode?order_sn=' + this.order_sn
              console.log(this.url)
              // global_.myVal = setInterval(this.getpayRes,1000);
              this.timer = setInterval(this.getpayRes, 1000);
            }
          })
      },
      getPayRequestDecount() {
        //http://taxlaw/open/payment/recharge_order?order_sn=202103042055334560&payment_code=balance
        axios.get('http://app.yejianping.cn/open/payment/recharge_order?order_sn=' + this.order_sn + '&payment_code=balance')
          .then((res) => {
            if (res.status == 200) {


              this.timer = setInterval(this.getpayRes, 3000);
            } else {
              let msg = res.message
              this.$message({
                dangerouslyUseHTMLString: true,
                message: msg,
                center: true,
                offset: 300,
                duration: 1000,
                type: 'warning'
              })
            }
          })
      },
      // getpayRes(){
      //   console.log(1)
      // },

      // test(){

      //   clearInterval(global_.myVal)
      //   this.$message({
      //                   dangerouslyUseHTMLString: true,
      //                   message: '<p>支付成功</p>',
      //                   center:true,
      //                   offset:300,
      //                   duration:1000,
      //                   type: 'success'
      //               })
      //           this.pay=false
      // }
      getpayRes() {
        let sn = this.order_sn
        axios.get('payment/query_state?order_sn=' + sn)
          .then((res) => {
            console.log(res.data.msg)
            if (res.data.msg == 'success') {
              // clearInterval(global_.myVal)
              clearInterval(this.timer);　　// 清除定时器
              this.timer = null;
              // this.$message({
              //   dangerouslyUseHTMLString: true,
              //   message: '<p>支付成功</p>',
              //   center: true,
              //   offset: 300,
              //   duration: 1000,
              //   type: 'success'
              // })
              this.pay = false
            } else {
              console.log('还未成功')
            }
          })
      }
    },
    async created() {
      var myVal;
      //this.getpayRes(),
      this.user = await updateUserInfo();
      const result = await axios.get('config/index')
      console.log(result)
      this.config = result.data.data

      window.addEventListener('setItem', () => {
        //this.pay = false

        this.form.amount = JSON.parse(storage.get('user')).amount_desc;
        this.expiretime = JSON.parse(storage.get('user')).lever_expire_time;
      })
      this.form.amount = JSON.parse(storage.get('user')).amount_desc;
      this.expiretime = JSON.parse(storage.get('user')).lever_expire_time;
      console.log(this.expiretime)
    },

  }
</script>

<style scoped>
  .to-pay {
    background: #fbd49b;
    border-radius: 40px;
    height: 50px;
    width: 150px;
  }

  .userform>>>.el-input__inner {
    width: 130px;
  }

  .userform>>>.readonly .el-input__inner {
    border-bottom: none;
  }

  .userform>>>.balance .el-input__inner {
    font-size: 20px;
    color: #0e79ed;
    font-family: "Gilroy-Regular" !important;
  }

  .userform>>>.red .el-input__inner {
    font-size: 20px;
    color: #ed0e51;
    font-family: "Gilroy-Regular" !important;
  }

  .userform .el-form-item {
    margin-bottom: 10px;
  }

  .userform>>>.el-radio-button__inner {
    display: flex;
    flex-direction: row;
    justify-content: center;
    width: 152px;
    height: 46px;
    line-height: 46px;
    border-radius: 0;
    margin-right: 30px;
    padding: 0;
    font-weight: 100;
    border: 1px solid #535353;
  }

  .userform>>>.el-radio-button.is-active.wxpay_native .el-radio-button__inner {
    border-color: #02bb29;
    background: #02bb29;
  }

  .userform>>>.el-radio-button.wxpay_native .el-radio-button__inner:hover {
    color: #02bb29;
    border-color: #02bb29;
  }

  .userform>>>.el-radio-button.wxpay_native.is-active .el-radio-button__inner:hover {
    color: #fff;
  }

  .userform>>>.el-radio-button.is-active.alipay .el-radio-button__inner {
    border-color: #409EFF;
  }

  .userform>>>.el-radio-button.alipay .el-radio-button__inner:hover {
    border-color: #409EFF;
  }

  .paymode .iconwxpay_native {
    font-size: 30px;
    margin-right: 15px;
  }

  .paymode .icon-alipay {
    font-size: 35px;
    margin-right: 10px;
  }

  .userform>>>.el-checkbox__label {
    font-size: 12px;
    font-weight: 300;
    color: #666;
  }

  .userform>>>.el-checkbox__inner {
    border-radius: 50%;
  }

  .codebox {
    width: 150px;
    height: 150px;
    background: #fff;
    margin-top: 30px;
    margin-left: 90px;
  }

  .codebox>img {
    width: 140px;
    height: 140px;
    margin-top: 5px;
    margin-left: 5px;
  }


  .usertop.flexrow {
    align-items: center;
  }

  .el-icon-success {
    font-size: 50px;
    color: #02bb29;
    margin-right: 25px;
  }

  .userform {
    height: 400px;
  }

  .moneyinput {
    width: 100px;
  }

  .tips {
    color: #909399;
    padding-left: 35px;
    width: 500px;
    align-items: baseline;
  }

  .tips i {
    margin-right: 10px;
  }

  .tips span {
    color: #333;
    font-weight: 600;
  }

  .bluebtn {
    padding: 5px 35px;
    border-radius: 20px;
    float: right;
    margin-right: 100px;
  }

  .iframeBox {
    position: relative;
  }

  #payiframe {
    z-index: 888;
  }

  .iframeBox button {
    position: absolute;
    top: 50px;
    right: 20px;
    z-index: 999;
  }

  .el-input.inline {
    width: auto;
  }

  .addmargin {
    margin: 0;
  }
</style>